package org.puremvc.as3.demos.flex.cafetownsend.model
{
	import com.salesforce.AsyncResponder;
	import com.salesforce.Connection;
	import com.salesforce.objects.LoginRequest;
	import com.salesforce.results.Fault;
	import com.salesforce.results.LoginResult;
	import com.salesforce.results.QueryResult;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	
	import org.puremvc.as3.demos.flex.cafetownsend.ApplicationFacade;
	import org.puremvc.as3.demos.flex.cafetownsend.model.business.LoadContactsDelegate;
	import org.puremvc.as3.demos.flex.cafetownsend.view.EmployeeLoginMediator;
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;

	public class ContactsProxy extends Proxy implements IProxy
	{

		public static const NAME:String = "ContactsProxy";
		
		private var force:Connection = new Connection();
		private var lr:LoginRequest = new LoginRequest();
		
		
		public function ContactsProxy(data:Object = null)
		{
			super(NAME, data);
		}
		
		public function loginToSalesForce(uname:String, pwd:String):void {
			if(uname != null && pwd != null)
			{
				var lr:LoginRequest = new LoginRequest();
				lr.username = "sandeeppatil.2020@gmail.com";
				lr.password = "sandeep_11"+"FPR6R4JTrGi4TCWHIPYI3XBZ";
				lr.callback = new AsyncResponder(loginSuccess, loginFailure);
				force.login(lr);
			}
			
		}
		
		private function loginSuccess(result:LoginResult):void
		{
			sendNotification(ApplicationFacade.VIEW_EMPLOYEE_LIST);
			Alert.show("Login Success");
			force.query("SELECT Id,CreatedDate,Email,FirstName,LastName FROM Contact", new AsyncResponder(queryResult));
		}
		
		private function loginFailure(event:Fault):void {
			Alert.show("Login Failure");
		}
		
		public function queryResult(result:QueryResult):void {
			data = result.records;
			Alert.show("Contacts:"+data.length);
			sendNotification( ApplicationFacade.LOAD_EMPLOYEES_SUCCESS );
		}
		
		public function get contactsListDP():ArrayCollection
		{
			return data as ArrayCollection;
		}
		
	}
}